import React from 'react';

import Form from 'antd/lib/form';
import 'antd/lib/form/style';
import Input from 'antd/lib/input';
import 'antd/lib/input/style';
import Button from 'antd/lib/button';
import 'antd/lib/button/style';
import Row from 'antd/lib/row';
import 'antd/lib/row/style';
import Col from 'antd/lib/col';
import 'antd/lib/col/style';
import Cascader from 'antd/lib/cascader';
import 'antd/lib/cascader/style';
import Checkbox from 'antd/lib/checkbox';
import { connect } from 'react-redux';
import { getHospital } from '../actions/sign';
import { EMAIL_REGEX } from '../config';

import { Link } from 'react-router';

const FormItem = Form.Item;
const createForm = Form.create;
import Select from 'antd/lib/select';
const Option = Select.Option;

const styles = {
    form: {
    },
    input: {
        backgroundColor: "rgba(255, 255, 255, 0.3",
    },
    label: {
        textAlign: "center",
        fontSize: "1.5rem",
        color: "#858585"
    }
}

function illegalChar(str)
{
    var pattern= EMAIL_REGEX;
    console.log(pattern);
    if(pattern.test(str)){  
        return false;     
    }     
    return true;  
}

class Register extends React.Component {

    constructor(props) {
        super(props);
        this.handleSubmit = this.handleSubmit.bind(this);
        this.handleReset = this.handleReset.bind(this);
        this.onAddressChange = this.onAddressChange.bind(this);
        this.state = {
            check:false
        }
        this.needChangeHospital = [];
    }

    componentDidMount() {
        if (this.props.defaultValue) {
            this.props.getHospital(this.props.defaultValue[0],this.props.defaultValue[1]);
            this.needChangeHospital = this.props.defaultValue;
        }
    }

    handleSubmit(event) {
        var evn = event || window.event;   
        if (evn.preventDefault) {    
            evn.preventDefault();   
        } else { 
            window.event.returnValue = false;   
        }  
        this.props.form.validateFields((error , values) => {
            if (!!error) {
                return ;
            }
            this.props.handleSubmit(values);
        });
    }

    handleReset(e) {
        e.preventDefault();
        this.setState({check:false});
        this.props.form.resetFields();
    }

    onAddressChange(rule, value, callback) {
        if (value instanceof Array && value.length >=2) {
            this.props.getHospital(value[0],value[1]);
            if (value.toString() != this.needChangeHospital.toString()) {
                this.needChangeHospital = value;
                this.props.form.resetFields(["hospital"]);
            }
            callback();
        } else {
            callback([new Error("请选择省市")]);
        }
    }

    onAgreement(rule, value, callback) {
        if (value === true) {
            callback();
        } else {
            callback([new Error("请同意并接受我们的服务条款")]);
        }
    }

    onTelNumber(rule, value ,callback) {
        if( value === undefined || value.length == 0  || (/^1[34578]\d{9}$/.test(value))){
            callback();
        } else {
            callback([new Error("请填写正确的手机号码")]);
        }
    }

    onHospital(rule, value ,callback) {
        if( value != undefined && value.length != 0 ){
            if(value.length > 30) {
                callback([new Error("内容不要超过30个字。")]);   
            } else if (illegalChar(value)) {
                callback();
            } else {
                callback([new Error("包含非法字符")]);    
            }
        } else {
            callback([new Error("请选择所属医院")]);
        }
    }

    charCheck(rule, value, callback) {
        if( value != undefined && value.length != 0 ){
            if(value.length > 30) {
                callback([new Error("内容不要超过30个字。")]);   
            } else if (illegalChar(value)) {
                callback();
            } else {
                callback([new Error("包含非法字符")]);    
            }
        } else {
            callback();
        }
    }

    render() {

        const options = this.props.cities;
        let hospital = [];
        if (this.props.hospital) {
            hospital = this.props.hospital;
        }

        const { getFieldProps, getFieldError, isFieldValidating } = this.props.form;
        let defaultValue = ['其他', '其他'];

        const addressProps = getFieldProps('address', {
            rules: [{ validator: this.onAddressChange }],
            initialValue:defaultValue
        });
        const hospitalProps = getFieldProps('hospital', {
            rules: [
                { validator: this.onHospital},  
            ],
        });
        const departmentProps = getFieldProps('department', {
            rules: [
                { required: true, whitespace: true, message: '请填写所属部门' },
                { validator: this.charCheck },  
            ],
        });
        const jobTitleProps = getFieldProps('jobTitle', {
            rules: [
                { required: true, whitespace: true, message: '请填写您的职称' },
                { validator: this.charCheck },  
            ],
        });
        const nameProps = getFieldProps('name', {
            rules: [
                { validator: this.charCheck },  
            ],
        });
        const telNumberProps = getFieldProps('telNumber', {
            rules: [
                { validator: this.onTelNumber }
            ],
        });
        const emailProps = getFieldProps('email', {
            rules: [
                { type: 'email', message: '请输入正确的邮箱地址' },
            ],
        });
        
        const agreementProps = getFieldProps('agreement', {
            rules: [
                { validator: this.onAgreement },
            ],
        });

        var reviewerRegLink = "reviewer/" + this.props.openId;

        return (
            <Form horizontal onSubmit={this.handleSubmit} style={styles.form}>
                <FormItem>
                    <Cascader {...addressProps} allowClear={false} options={options} placeholder="请选择地区"  style={styles.input} />
                </FormItem>
                <FormItem
                    >
                    <Select {...hospitalProps} combobox placeholder="输入医院名" style={{ width: "100%" }}>
                        { 
                            hospital.map(function(item){
                                let key = new Date()
                                return (<Option key={item.Hospital} value={item.Hospital}>{item.Hospital}</Option>);
                            })
                        }
                    </Select>
                </FormItem>
                <FormItem
                    >
                    <Input {...departmentProps} placeholder="所属部门" style={styles.input}/>
                </FormItem>
                <FormItem
                    >
                    <Input {...jobTitleProps} placeholder="职称" style={styles.input}/>
                </FormItem>
                <FormItem
                    >
                    <Input {...nameProps} placeholder="姓名" style={styles.input}/>
                </FormItem>
                <FormItem
                    >
                    <Input {...telNumberProps} placeholder="手机" style={styles.input}/>
                </FormItem>
                <FormItem
                    >
                    <Input {...emailProps} placeholder="邮箱" style={styles.input}/>
                </FormItem>
                <FormItem>
                    <Checkbox {...agreementProps} checked={this.state.check} onClick={()=>{this.setState({check:!this.state.check})}}>同意</Checkbox><a onClick={this.props.showLegal}>服务规约</a>
                    <Link to={reviewerRegLink} className="pull-right">内部员工注册</Link>
                </FormItem>
                <Row>
                    <Col span={12} style={{ textAlign: 'center' }}>
                        <Button style={{width:"95%",marginRight:"5%"}} type="primary" htmlType="submit">注册</Button>
                    </Col>
                    <Col span={12} style={{ textAlign: 'center' }}>
                        <Button style={{width:"95%",marginLeft:"5%"}} onClick={this.handleReset}>重置</Button>
                    </Col>
                </Row>
            </Form>
        );
    }
}

Register = createForm()(Register);

function mapStateToProps(state) {
    return {
        initProfile: state.sign.userInfo,
        hospital: state.sign.hospitals
    }
}

export default connect(mapStateToProps, { getHospital })(Register);